#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>

#include<string.h>


//利用冒泡排序模拟实现qsort函数
void Swap(char* buf1, char* buf2,int size)//交换arr[j]和arr[j+1]这两个元素
{
	int i = 0;
	char temp = 0;
	for (i = 0; i < size; i++)
	{
		temp = *buf1;
		*buf1 = *buf2;
		*buf2 = temp;
		buf1++;
		buf2++;
	}
}
void my_bubble_qsort(void* base, int num, int size,int (*cmp)(const void*,const void*))
{
	int i = 0;
	for (i = 0; i < num - 1; i++)
	{
		int j = 0;
		for (j = 0; j < num - 1 - i; j++)
		{
			//假设需要升序，>0就交换
			if (cmp((char*)base + j * size, (char*)base + (j + 1) * size) > 0)//两个元素比较，需要将arr[j]，arr[j+1]的地址传给cmp
			{
				//交换函数
				Swap((char*)base + j * size, (char*)base + (j + 1) * size,size);
			}
		}
	}
}


//一、测试排序整型数据
int cmp_int(const void* p1, const void* p2)
{
	return *(int*)p1 - *(int*)p2;//升序
}
void test1()
{
	int arr[10] = { 1,3,5,7,9,2,4,6,8,10 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	my_bubble_qsort(arr, sz, sizeof(arr[0]), cmp_int);
}

//二、测试排序结构体数据——年龄
struct Stu
{
	char name[20];
	int age;
};
int cmp_struct_age(const void* p1, const void* p2)
{
	return ((struct Stu*)p1)->age - ((struct Stu*)p2)->age;
}
void test2()
{
	struct Stu arr[3] = { {"zhangsan",15},{"lisi",50},{"wangwu",20} };
	int sz = sizeof(arr) / sizeof(arr[0]);
	my_bubble_qsort(arr, sz, sizeof(arr[0]), cmp_struct_age);
}

//三、测试排序结构体数据——名字
int cmp_struct_name(const void* p1, const void* p2)
{
	return strcmp(((struct Stu*)p1)->name, ((struct Stu*)p2)->name);
}
void test3()
{
	struct Stu arr[3] = { {"zhangsan",15},{"lisi",50},{"wangwu",20} };
	int sz = sizeof(arr) / sizeof(arr[0]);
	my_bubble_qsort(arr, sz, sizeof(arr[0]), cmp_struct_name);
}
int main()
{
	//test1();
	//test2();
	test3();
	return 0;
}